/*
 *  Copyright 2011 David Audrain
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.bmha.ui;

import java.lang.ref.WeakReference;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;


abstract class BitmapDrawableSetter extends ResourceSetter
{
  private final WeakReference<Resources> resources;
  private final WeakReference<BitmapFactory.Options> options;
  private int resid = -1;
  private Bitmap bitmap;
  private BitmapDrawable drawable;
  
  BitmapDrawableSetter(Resources resources, BitmapFactory.Options options)
  {
    this.resources = new WeakReference<Resources>(resources);
    this.options = new WeakReference<BitmapFactory.Options>(options);
  }
  
  private void cleanInternals()
  {
    if (bitmap != null)
    {
      bitmap.recycle();
      bitmap = null;
    }
    if (drawable != null)
    {
      drawable.setCallback(null);
      drawable = null;
    }
  }
  
  protected abstract void setDrawable(Drawable drawable);
  
  public void setResource(int newid)
  {
    final Resources resources = this.resources.get();
    final BitmapFactory.Options options = this.options.get();
    if (newid != resid && resources != null && options != null)
    {
      final Bitmap newBitmap = BitmapFactory.decodeResource(resources, newid, options);
      final BitmapDrawable newDrawable = new BitmapDrawable(resources, newBitmap);
      setDrawable(newDrawable);
      cleanInternals();
      bitmap = newBitmap;
      drawable = newDrawable;
      resid = newid;
    }
  }
  public void onDestroy()
  {
    cleanInternals();
  }
}
